package com.saunter.filter;

import com.saunter.utils.ConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpHeaders;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebFilter(urlPatterns = {"/*"},filterName = "corsFilter")
//filter的优先级最高
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
    private static final String REQUEST_OPTIONS = "OPTIONS";
    @Autowired
    private ConfigProperties configProperties;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        ServletContext sc = filterConfig.getServletContext();
        WebApplicationContext cxt = WebApplicationContextUtils.getWebApplicationContext(sc);
        if(cxt != null && cxt.getBean(ConfigProperties.class) != null && configProperties == null) {
            configProperties =cxt.getBean(ConfigProperties.class);
        }
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest servletRequest1 = (HttpServletRequest)servletRequest;
        HttpServletResponse servletResponse1 = (HttpServletResponse)servletResponse;

        List<String> cors_origins = configProperties.getCors_origin();
        if(null != cors_origins && 0 < cors_origins.size()) {
            String request_origin = servletRequest1.getHeader(HttpHeaders.ORIGIN);
            if(null != request_origin && ("*".equals(cors_origins.get(0)) || cors_origins.contains(request_origin))) {
                servletResponse1.addHeader("Access-Control-Allow-Origin", request_origin);
                //允许带cookie凭证
                servletResponse1.addHeader("Access-Control-Allow-Credentials", "true");
                servletResponse1.addHeader("Access-Control-Allow-Methods", "POST, GET");
                servletResponse1.addHeader("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With");
                //返回结果可用于缓存的最长事件，单位秒，-1禁用
                servletResponse1.addHeader("Access-Control-Allow-Max-Age", "3600");
                //跨域预检请求，直接返回
                if (REQUEST_OPTIONS.equalsIgnoreCase(servletRequest1.getMethod())) {
                    return;
                }
            }
        }
        filterChain.doFilter(servletRequest1, servletResponse);
    }
    @Override
    public void destroy() {

    }
}
